<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'misc/inet_functions.inc.php');


require_once('vl_language_dbc.class.php');
require_once('visitor_language_dbc.class.php');


require_once('te_lda_cannot_update_vl.class.php');


class Language_Detector_Advanced extends Tangra_Class {
	private $context;
	private $dbc;

	function __construct(Web_Context $context, DB_Connection $dbc) {
		$this->context = $context;
		$this->dbc = $dbc;
	}


	public function detect_language($available_languages_arr, $visitor_id, $ld_var_name = '_lang', $ld_lang_switch = '_lang_switch') {
		tangra_if_not_int_throw_e($visitor_id);
		$lang = false;

		if ($this->context->exists_in_get($ld_lang_switch)) {
			$tmp = $this->context->get_from_get($ld_lang_switch);
			if (in_array($tmp, $available_languages_arr)) {
				$lang = $tmp;
				$this->update_visitors_language($visitor_id, $lang);
			}
		} else {
			if ($this->context->exists_in_pi($ld_var_name)) {
				$lang = $this->context->get_from_pi($ld_var_name);
			} else {
				$tmp = $this->search_for_visitor_language_in_db($visitor_id);

				if ($tmp !== false) {
					if (in_array($tmp, $available_languages_arr)) {
						$lang = $tmp;
					}
				} else {
					$tmp = $this->detect_language_by_browser_settings($available_languages_arr);
					if ($tmp !== false) {
						$lang = $tmp;
						$this->update_visitors_language($visitor_id, $lang);
					}
				}
			}
		}


		return $lang;
	}


	private function search_for_visitor_language_in_db($visitor_id) {
		$ret = false;

		$vl = new Visitor_Language_DBC();
		if ($vl->load_by_visitor_id($this->dbc, $visitor_id)) {
			$lang_id = $vl->get_language();
			if ($lang_id) {
				$vl_language = new VL_Language_DBC();
				if ($vl_language->load_by_id($this->dbc, $lang_id)) {
					$ret = $vl_language->get_code();
				}
			}

		}

		return $ret;
	}


	private function detect_language_by_browser_settings($available_languages_arr) {
		$ret = false;

		if ($this->context->exists_in_server('HTTP_ACCEPT_LANGUAGE')) {
			$lang_arr = parse_http_accept_language($this->context->get_from_server('HTTP_ACCEPT_LANGUAGE'));
			foreach($lang_arr as $lang) {
				if (in_array($lang['lang_code'], $available_languages_arr)) {
					$ret = $lang['lang_code'];
					break;
				}
			}
		}

		return $ret;
	}



	private function update_visitors_language($visitor_id, $lang) {
		$vl_language = new VL_Language_DBC();
		if ($vl_language->load_by_code($this->dbc, $lang)) {
			$vl = new Visitor_Language_DBC();
			if ($vl->load_by_visitor_id($this->dbc, $visitor_id)) {
				$vl->set_language($vl_language->get_id());
			} else {
				$vl->set_visitor($visitor_id);
				$vl->set_language($vl_language->get_id());
			}

			$vl->save($this->dbc);
		} else {
			throw new TE_LDA_Cannot_Update_VL();
		}
	}
}